import React, { useEffect, useState } from 'react';
import { useDispatch, connect } from 'umi';
import { Column } from '@ant-design/plots';
import {
  Card,
  Col,
  Collapse,
  Cascader,
  Divider,
  Row,
  Table,
  Select,
  Tooltip,
  Spin,
} from 'antd';

const { Panel } = Collapse;

const WarningAnalyse = (props: any) => {
  const [selectedData, setSelectedData] = useState(null); // 存储选定的条形图的数据
  const [isLoading, setIsLoading] = useState(true); // 数据加载状态
  const handleElementClick = (event: any) => {
    const { data } = event; // 获取被点击柱状图元素对应的数据
    console.log(data);
    setSelectedData(data); // 将数据存储到 selectedData 状态变量中
  };

  const columns = [
    {
      title: '班级名称',
      dataIndex: 'classLabel',
    },
    {
      title: '一级预警人数占比',
      dataIndex: 'alert1',
    },
    {
      title: '二级预警人数占比',
      dataIndex: 'alert2',
    },
    {
      title: '三级预警人数占比',
      dataIndex: 'alert3',
    },
  ];

  const dispatch = useDispatch();
  //表格数据
  const [result, setResult] = useState([]);
  const [resultCopy, setResultCopy] = useState([]);
  //柱状图数据
  const [data, setData] = useState([]);
  const [dataCopy, setDataCopy] = useState([]);
  //柱状图配置
  const config = {
    data,
    isGroup: true,
    xField: 'classLabel',
    yField: 'warningRate',
    seriesField: 'name',
    color: ['#FFD700', '#FFA500', '#FF0000'],
    label: {
      // 可手动配置 label 数据标签位置
      position: 'bottom-left',
      // 'top', 'middle', 'bottom'
      formatter: (item) => {
        let newValue = Math.round(item.warningRate * item.totalClassSize); // 进一步计算
        return `${newValue}人`; // 显示格式化后的数据
      },
      style: {
        fill: '#000',
        fontSize: 12,
        fontWeight: 'bold',
      },
      // 可配置附加的布局方法
      layout: [
        // 柱形图数据标签位置自动调整
        {
          type: 'interval-adjust-position',
        }, // 数据标签防遮挡
        {
          type: 'interval-hide-overlap',
        }, // 数据标签文颜色自动调整
        {
          type: 'adjust-color',
        },
      ],
    },
    onReady: (plot) => {
      // 绑定柱状图元素的点击事件
      plot.on('element:click', handleElementClick);
    },
  };
  useEffect(() => {
    setIsLoading(true); // 设置加载状态为 true
    //获取数据接口
    dispatch({
      type: 'Model_StudentAnalysisStudentModel/getPrecautionAnalysisEffects',
      payload: {
        studentCode: JSON.parse(props.user.currrentuser).account,
        callback: (value: any) => {
          // console.log(value);
          setResult(value);
          setResultCopy(value);
          //将表格数据结构转化为柱状图
          const transformedData = value.flatMap((item) => {
            // console.log(item)
            const { classLabel, alert1, alert2, alert3, totalClassSize } = item;
            return [
              {
                name: '一级预警人数占比',
                classLabel: classLabel,
                warningRate: parseFloat(alert1) / 100,
                totalClassSize: totalClassSize,
              },
              {
                name: '二级预警人数占比',
                classLabel: classLabel,
                warningRate: parseFloat(alert2) / 100,
                totalClassSize: totalClassSize,
              },
              {
                name: '三级预警人数占比',
                classLabel: classLabel,
                warningRate: parseFloat(alert3) / 100,
                totalClassSize: totalClassSize,
              },
            ];
          });
          setData(transformedData);
          setDataCopy(transformedData);
          setIsLoading(false); // 数据加载完成后，设置加载状态为 false
        },
      },
    });
  }, []);

  // 横向柱状图专业过滤
  const handleMajorChange = (value: string) => {
    let list: { name: string; classLabel: string; warningRate: number }[] = [];
    if (value === '新能') {
      list = dataCopy.filter((item) => item.classLabel.includes('新能')); //Array.filter()保留参数为true的那一项
    } else if (value === '电气') {
      list = dataCopy.filter((item) => !item.classLabel.includes('新能'));
    }
    setData(list);
  };

  // 横向表格专业过滤
  const handleMajorChangeTable = (data: string) => {
    let list1: {
      classLabel: string;
      alert1: string;
      alert2: string;
      alert3: string;
    }[] = [];
    if (data === '新能') {
      list1 = resultCopy.filter((item) => item.classLabel.includes('新能')); //Array.filter()保留参数为true的那一项
    } else if (data === '电气') {
      list1 = resultCopy.filter((item) => !item.classLabel.includes('新能'));
    }
    setResult(list1);
  };

  //纵向级联选择器
  const options = [
    {
      value: '新能源科学与工程',
      label: '新能源科学与工程',
      children: [
        {
          value: '新能01',
          label: '新能201',
        },
        {
          value: '新能02',
          label: '新能202',
        },
      ],
    },
    {
      value: '电气工程及其自动化',
      label: '电气工程及其自动化',
      children: [
        {
          value: '电气01',
          label: '电气2001',
        },
        {
          value: '电气02',
          label: '电气2002',
        },
        {
          value: '电气03',
          label: '电气2003',
        },
      ],
    },
  ];
  function onChange(value) {
    console.log(value);
  }
  return (
    <div>
      <Card
        title={
          <span style={{ fontWeight: 'bold', fontSize: 18 }}>
            班级间预警情况对比
          </span>
        }
      >
        {/* 第一行 */}
        <Row gutter={8}>
          <Col span={12}>
            <Collapse defaultActiveKey={['1']}>
              <Panel
                header={
                  <Tooltip title="专业内横向班级间对比，展示辅导员对应年级下，每个班级一、二、三级预警下人数与班级人数占比">
                    <div>班级间横向对比条形图</div>
                  </Tooltip>
                }
                key="1"
              >
                <Card
                  title={'班级间横向对比条形图'}
                  extra={
                    <Select
                      placeholder={'选择专业'}
                      style={{ width: 200 }}
                      onChange={handleMajorChange}
                    >
                      <Select.Option value="新能">
                        新能源科学与工程
                      </Select.Option>
                      <Select.Option value="电气">
                        电气工程及其自动化
                      </Select.Option>
                    </Select>
                  }
                >
                  {isLoading ? ( // 根据加载状态显示加载提示或柱状图
                    <div style={{ textAlign: 'center' }}>
                      <Spin />
                      <div>数据正在加载...</div>
                    </div>
                  ) : (
                    <Column {...config} />
                  )}
                </Card>
              </Panel>
            </Collapse>
          </Col>
          <Col span={12}>
            <Collapse defaultActiveKey={['1']}>
              <Panel
                header={
                  <Tooltip title="专业内，横向对比往届各一、二、三预警情况">
                    <div>班级间横向对比表格</div>
                  </Tooltip>
                }
                key="1"
              >
                <Card
                  title={'班级间横向对比表格'}
                  extra={
                    <Select
                      placeholder={'选择专业'}
                      style={{ width: 200 }}
                      onChange={handleMajorChangeTable}
                    >
                      <Select.Option value="新能">
                        新能源科学与工程
                      </Select.Option>
                      <Select.Option value="电气">
                        电气工程及其自动化
                      </Select.Option>
                    </Select>
                  }
                >
                  {isLoading ? ( // 根据加载状态显示加载提示或表格
                    <div style={{ textAlign: 'center' }}>
                      <Spin />
                      <div>数据正在加载...</div>
                    </div>
                  ) : (
                    <Table
                      columns={columns}
                      dataSource={result}
                      pagination={{
                        pageSize: 5,
                        showSizeChanger: true,
                        pageSizeOptions: ['5', '10'],
                      }}
                    />
                  )}
                </Card>
              </Panel>
            </Collapse>
          </Col>
        </Row>
        {/* 第二行 */}
        <Row gutter={8}>
          <Col span={12}>
            <Collapse defaultActiveKey={['3']}>
              <Panel
                header={
                  <Tooltip title="专业内纵向班级间对比，展示辅导员对应班级下，每个班级一、二、三级预警下人数与班级人数占比">
                    <div>班级间纵向对比条形图</div>
                  </Tooltip>
                }
                key="3"
              >
                <Card
                  title={'班级间纵向对比条形图'}
                  extra={
                    <Cascader
                      options={options}
                      onChange={onChange}
                      placeholder="请选择班级"
                    />
                  }
                >
                  {isLoading ? ( // 根据加载状态显示加载提示或柱状图
                    <div style={{ textAlign: 'center' }}>
                      <Spin />
                      <div>数据正在加载...</div>
                    </div>
                  ) : (
                    <Column {...config} />
                  )}
                </Card>
              </Panel>
            </Collapse>
          </Col>
          <Col span={12}>
            <Collapse defaultActiveKey={['4']}>
              <Panel
                header={
                  <Tooltip title="专业内，纵向对比往届各一、二、三预警情况">
                    <div>班级间纵向对比表格</div>
                  </Tooltip>
                }
                key="4"
              >
                <Card
                  title={'班级间纵向对比表格'}
                  extra={
                    <Cascader
                      options={options}
                      onChange={onChange}
                      placeholder="请选择班级"
                    />
                  }
                >
                  {isLoading ? ( // 根据加载状态显示加载提示或表格
                    <div style={{ textAlign: 'center' }}>
                      <Spin />
                      <div>数据正在加载...</div>
                    </div>
                  ) : (
                    <Table
                      columns={columns}
                      dataSource={result}
                      pagination={{
                        pageSize: 5, // 每页展示的行数
                        showSizeChanger: true, // 允许用户切换每页展示的行数
                        pageSizeOptions: ['5', '10', '20', '50'], // 切换的行数选项
                      }}
                    />
                  )}
                </Card>
              </Panel>
            </Collapse>
          </Col>
        </Row>
        <Divider />
      </Card>
    </div>
  );
};

export default connect(({ Model_StudentAnalysisStudentModel, user }: any) => ({
  Model_StudentAnalysisStudentModel,
  user,
}))(WarningAnalyse);
